import 'package:flutter/cupertino.dart';
import 'package:get/get.dart';
import 'package:quick_code_platform/constant/constant.dart';
import 'package:quick_code_platform/http/page_api.dart';
import 'package:dio/dio.dart';
import 'package:quick_code_platform/routes/quick_app_routes.dart';
import 'package:quick_code_platform/util/permission_utils.dart';
import 'package:quick_code_platform/custom/custom_dialog/get_widget_dialog_view.dart';
import 'package:quick_code_platform/custom/custom_dialog/progress_dialog_view.dart';
import 'package:package_info/package_info.dart';
import 'package:permission_handler/permission_handler.dart';

import '../../routes/routes.dart';

class BaseController extends GetxController {
  CancelToken? canelToken;

  @override
  void onInit() {
    super.onInit();
    canelToken = CancelToken();
  }

  saveUpdateApp(
      {bool isUpdate = false,
      bool isGuide = false,bool isSetting = false}) async {
    List<Permission> permissions = [
      Permission.storage,
      Permission.requestInstallPackages
    ];
    PermissionUtils.check(permissions,
        onSuccess: () async {
          var info = await PageApi.syncInterface(
              "$quickCatalogueBaseUrl/Config.txt", canelToken,
              method: "GET");
          if (info.ok) {
            //文件地址可以请求成功
            int? c = info.data!["apkVersion"]
                .compareTo(Get.find<PackageInfo>().version);
            String? s = info.data!["apkUpdateDesc"];
            if (c == 1) {
              //有版本更新
              Get.dialog(
                  GetWidgetDialogWidget(
                    title: "发现新版本",
                    message: "更新内容\n${s!}",
                    confirmText: "立即更新",
                    onConfirmEvent: () {
                      Get.back();
                      downLoadApk(
                          "$quickCatalogueBaseUrl/${info.data!["apkUrl"]}");
                    },
                  ),
                  barrierDismissible: false);
            } else {
              //无版本更新 跳转入口页
              if (isUpdate) {
                showToast("已经是最新版本了");
              } else {
                if(isSetting){
                  // Get.back();
                  Get.offAllNamed(
                    QuickRoutes.index,
                    arguments: {'pageId': info.data!["enterFormId"]},
                  );
                }else{
                  Get.offAllNamed(
                    QuickRoutes.index,
                    arguments: {'pageId': info.data!["enterFormId"]},
                  );
                }

              }
            }
          } else {
            if (isGuide) {
              //文件地址请求失败
              Get.dialog(
                  WillPopScope(
                    onWillPop: () async => false,
                    child: GetWidgetDialogWidget(
                      title: "提示",
                      message: "配置文件地址请求失败，请重新检查",
                      onCancelEvent: () {
                        Get.back();
                        Get.offAndToNamed(Routes.setting,
                            arguments: {"isLocal": true,'isSetting' : false});
                      },
                      cancelText: "检查",
                      confirmText: "重试",
                      onConfirmEvent: () {
                        Get.back();
                        saveUpdateApp(isGuide: true);
                      },
                    ),
                  ),
                  barrierDismissible: false);
            } else {
              //文件地址请求失败
              Get.dialog(WillPopScope(
                onWillPop: () async => false,
                child: GetWidgetDialogWidget(
                  title: "提示",
                  message: "配置文件地址请求失败，请重新检查",
                  onCancelEvent: () {
                    Get.back();
                  },
                  cancelText: "取消",
                  confirmText: "重试",
                  onConfirmEvent: () {
                    Get.back();
                    saveUpdateApp();
                  },
                ),
              ));
            }
          }
        },
        onFailed: () {},
        onOpenSetting: () {
          openAppSettings();
        });
  }

  void downLoadApk(String? resourceUrl) {
    Get.dialog(
        ProgressDialogWidget(
          title: "文件下载中",
          url: resourceUrl ?? "",
        ),
        barrierDismissible: false);
  }
}
